<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>tools</title>
</head>

<body>
    <div id="back">返回</div>
    <div class="box">
        <input id="file" type="file">
    </div>
    <script type="module">
        const oBackBtn = document.getElementById('back')
        oBackBtn.onclick = () => {
            window.history.back()
        }
        const chunkFiles = (files, chunkSize = 1024 * 1024) => {
            const chunks = []
            for (let i = 0; i < files.size; i += chunkSize) {
                const chunk = files.slice(i, i + chunkSize)
                chunks.push(chunk)
            }
            return chunks
        }

        const uploadFile = (file, index, name) => {

        }

        const handleChange = (e) => {

        }

        const fileInput = document.getElementById('file');
        fileInput.addEventListener('change', (event) => {
            const uploadFile = (file, index, name) => {
                const formData = new FormData()
                formData.append('index', index)
                formData.append('name', name)
                formData.append('file', file)
                return fetch('http://localhost:9527/tools/upload', {
                    method: 'POST',
                    body: formData
                }).then(res => res.json())
            }
            const file = event.target.files[0]
            const chunks = chunkFiles(file)
            const res = []
            for (let i in chunks) {
                res.push(uploadFile(chunks[i], i, file.name))
            }
            Promise.all(res).then(data => {
                fetch('http://localhost:9527/tools/merge', {
                    method: 'POST',
                    body: JSON.stringify({
                        name: file.name
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(res => {
                    fetch('http://localhost:9527/tools/zip', {
                        method: 'POST',
                        body: JSON.stringify({
                            name: file.name,
                            quality: 50
                        }),
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }).then(res => {
                        return res.json()
                    }).then(res=>{
                        const img = document.createElement('img')
                        img.src =   `data:image/png;base64,${res.data.pic}`
                        img.style.width = '200px'
                        document.body.appendChild(img)
                    })
                })
            })
        });
    </script>
</body>

</html>